{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example of using the PyRadiomics toolbox in Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, import some built-in Python modules needed to get our testing data.\n",
    "Second, import the toolbox, only the `featureextractor` is needed, this module handles the interaction with other parts of the toolbox."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import annotations\n",
    "\n",
    "import os  # needed navigate the system to get the input data\n",
    "\n",
    "import radiomics\n",
    "from radiomics import (\n",
    "    featureextractor,  # This module is used for interaction with pyradiomics\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setting up data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test cases can be downloaded to temporary files. This is handled by the `radiomics.getTestCase()` function, which checks if the requested test case is available and if not, downloads it. It returns a tuple with the location of the image and mask of the requested test case, or (None, None) if it fails.\n",
    "\n",
    "Alternatively, if the data is available somewhere locally, this directory can be passed as a second argument to `radiomics.getTestCase()`. If that directory does not exist or does not contain the testcase, functionality reverts to default and tries to download the test data.\n",
    "\n",
    "If getting the test case fails, PyRadiomics will log an error explaining the cause."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter file, absolute path: E:\\Git-Repos\\pyradiomics\\examples\\exampleSettings\\Params.yaml\n"
     ]
    }
   ],
   "source": [
    "# Get the testCase\n",
    "imagePath, maskPath = radiomics.getTestCase('brain1')\n",
    "\n",
    "if imagePath is None or maskPath is None:  # Something went wrong, in this case PyRadiomics will also log an error\n",
    "    msg = 'Error getting testcase!'\n",
    "    raise Exception(msg)  # Raise exception to prevent cells below from running in case of \"run all\"\n",
    "\n",
    "# Additionally, store the location of the example parameter file, stored in \\pyradiomics\\examples/exampleSettings\n",
    "paramPath = os.path.join('..', 'examples', 'exampleSettings', 'Params.yaml')\n",
    "print('Parameter file, absolute path:', os.path.abspath(paramPath))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Instantiating the extractor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have our input, we need to define the parameters and instantiate the extractor.\n",
    "For this there are three possibilities:\n",
    "\n",
    "1. Use defaults, don't define custom settings\n",
    "\n",
    "2. Define parameters in a dictionary, control filters and features after initialisation\n",
    "\n",
    "3. Use a parameter file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Method 1, use defaults"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extraction parameters:\n",
      "\t {'distances': [1], 'additionalInfo': True, 'force2D': False, 'interpolator': 'sitkBSpline', 'resampledPixelSpacing': None, 'label': 1, 'normalizeScale': 1, 'normalize': False, 'force2Ddimension': 0, 'removeOutliers': None, 'minimumROISize': None, 'minimumROIDimensions': 2, 'preCrop': False, 'resegmentRange': None, 'padDistance': 5}\n",
      "Enabled filters:\n",
      "\t {'Original': {}}\n",
      "Enabled features:\n",
      "\t {'gldm': [], 'glcm': [], 'shape': [], 'firstorder': [], 'glrlm': [], 'glszm': [], 'ngtdm': []}\n"
     ]
    }
   ],
   "source": [
    "# Instantiate the extractor\n",
    "extractor = featureextractor.RadiomicsFeatureExtractor()\n",
    "\n",
    "print('Extraction parameters:\\n\\t', extractor.settings)\n",
    "print('Enabled filters:\\n\\t', extractor.enabledImagetypes)\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Method 2, hard-coded settings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extraction parameters:\n",
      "\t {'distances': [1], 'additionalInfo': True, 'force2D': False, 'interpolator': 'sitkBSpline', 'resampledPixelSpacing': None, 'label': 1, 'normalizeScale': 1, 'normalize': False, 'force2Ddimension': 0, 'removeOutliers': None, 'minimumROISize': None, 'binWidth': 20, 'minimumROIDimensions': 2, 'preCrop': False, 'resegmentRange': None, 'sigma': [1, 2, 3], 'padDistance': 5}\n",
      "Enabled filters:\n",
      "\t {'Original': {}}\n",
      "Enabled features:\n",
      "\t {'gldm': [], 'glcm': [], 'shape': [], 'firstorder': [], 'glrlm': [], 'glszm': [], 'ngtdm': []}\n"
     ]
    }
   ],
   "source": [
    "# First define the settings\n",
    "settings = {}\n",
    "settings['binWidth'] = 20\n",
    "settings['sigma'] = [1, 2, 3]\n",
    "\n",
    "# Instantiate the extractor\n",
    "extractor = featureextractor.RadiomicsFeatureExtractor(**settings)  # ** 'unpacks' the dictionary in the function call\n",
    "\n",
    "print('Extraction parameters:\\n\\t', extractor.settings)\n",
    "print('Enabled filters:\\n\\t', extractor.enabledImagetypes)  # Still the default parameters\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)  # Still the default parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extraction parameters:\n",
      "\t {'distances': [1], 'additionalInfo': True, 'force2D': False, 'interpolator': 'sitkBSpline', 'resampledPixelSpacing': None, 'label': 1, 'normalizeScale': 1, 'normalize': False, 'force2Ddimension': 0, 'removeOutliers': None, 'minimumROISize': None, 'binWidth': 20, 'minimumROIDimensions': 2, 'preCrop': False, 'resegmentRange': None, 'sigma': [1, 2, 3], 'padDistance': 5}\n",
      "Enabled filters:\n",
      "\t {'Original': {}}\n",
      "Enabled features:\n",
      "\t {'gldm': [], 'glcm': [], 'shape': [], 'firstorder': [], 'glrlm': [], 'glszm': [], 'ngtdm': []}\n"
     ]
    }
   ],
   "source": [
    "# This cell is equivalent to the previous cell\n",
    "extractor = featureextractor.RadiomicsFeatureExtractor(binWidth=20, sigma=[1, 2, 3])  # Equivalent of code above\n",
    "\n",
    "print('Extraction parameters:\\n\\t', extractor.settings)\n",
    "print('Enabled filters:\\n\\t', extractor.enabledImagetypes)  # Still the default parameters\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)  # Still the default parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Enabled filters:\n",
      "\t {'Original': {}, 'LoG': {}}\n",
      "\n",
      "Enabled features:\n",
      "\t {'firstorder': []}\n",
      "\n",
      "Enabled features:\n",
      "\t {'firstorder': [], 'glcm': ['Autocorrelation', 'Homogeneity1', 'SumSquares']}\n"
     ]
    }
   ],
   "source": [
    "# Enable a filter (in addition to the 'Original' filter already enabled)\n",
    "extractor.enableImageTypeByName('LoG')\n",
    "print('')\n",
    "print('Enabled filters:\\n\\t', extractor.enabledImagetypes)\n",
    "\n",
    "# Disable all feature classes, save firstorder\n",
    "extractor.disableAllFeatures()\n",
    "extractor.enableFeatureClassByName('firstorder')\n",
    "print('')\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)\n",
    "\n",
    "# Specify some additional features in the GLCM feature class\n",
    "extractor.enableFeaturesByName(glcm=['Autocorrelation', 'Homogeneity1', 'SumSquares'])\n",
    "print('')\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Method 3, using a parameter file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extraction parameters:\n",
      "\t {'distances': [1], 'additionalInfo': True, 'weightingNorm': None, 'force2D': False, 'interpolator': 'sitkBSpline', 'resampledPixelSpacing': None, 'label': 1, 'normalizeScale': 1, 'normalize': False, 'force2Ddimension': 0, 'removeOutliers': None, 'minimumROISize': None, 'binWidth': 25, 'minimumROIDimensions': 2, 'preCrop': False, 'resegmentRange': None, 'padDistance': 5}\n",
      "Enabled filters:\n",
      "\t {'Original': {}}\n",
      "Enabled features:\n",
      "\t {'glcm': ['Autocorrelation', 'JointAverage', 'ClusterProminence', 'ClusterShade', 'ClusterTendency', 'Contrast', 'Correlation', 'DifferenceAverage', 'DifferenceEntropy', 'DifferenceVariance', 'JointEnergy', 'JointEntropy', 'Imc1', 'Imc2', 'Idm', 'Idmn', 'Id', 'Idn', 'InverseVariance', 'MaximumProbability', 'SumEntropy', 'SumSquares'], 'shape': None, 'gldm': None, 'firstorder': [], 'glrlm': None, 'glszm': None}\n"
     ]
    }
   ],
   "source": [
    "# Instantiate the extractor\n",
    "extractor = featureextractor.RadiomicsFeatureExtractor(paramPath)\n",
    "\n",
    "print('Extraction parameters:\\n\\t', extractor.settings)\n",
    "print('Enabled filters:\\n\\t', extractor.enabledImagetypes)\n",
    "print('Enabled features:\\n\\t', extractor.enabledFeatures)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Extract features"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have our extractor set up with the correct parameters, we can start extracting features:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "result = extractor.execute(imagePath, maskPath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Result type: <class 'collections.OrderedDict'>\n",
      "\n",
      "Calculated features\n",
      "\t diagnostics_Versions_PyRadiomics : 2.1.2.post68.dev0+g590d9fe\n",
      "\t diagnostics_Versions_Numpy : 1.15.1\n",
      "\t diagnostics_Versions_SimpleITK : 0.9.1\n",
      "\t diagnostics_Versions_PyWavelet : 0.5.2\n",
      "\t diagnostics_Versions_Python : 2.7.11\n",
      "\t diagnostics_Configuration_Settings : {'distances': [1], 'additionalInfo': True, 'weightingNorm': None, 'force2D': False, 'interpolator': 'sitkBSpline', 'resampledPixelSpacing': None, 'label': 1, 'normalizeScale': 1, 'normalize': False, 'force2Ddimension': 0, 'removeOutliers': None, 'minimumROISize': None, 'binWidth': 25, 'minimumROIDimensions': 2, 'preCrop': False, 'resegmentRange': None, 'padDistance': 5}\n",
      "\t diagnostics_Configuration_EnabledImageTypes : {'Original': {}}\n",
      "\t diagnostics_Image-original_Hash : 5c9ce3ca174f0f8324aa4d277e0fef82dc5ac566\n",
      "\t diagnostics_Image-original_Dimensionality : 3D\n",
      "\t diagnostics_Image-original_Spacing : (0.7812499999999999, 0.7812499999999999, 6.499999999999998)\n",
      "\t diagnostics_Image-original_Size : (256, 256, 25)\n",
      "\t diagnostics_Image-original_Mean : 385.6564080810547\n",
      "\t diagnostics_Image-original_Minimum : 0.0\n",
      "\t diagnostics_Image-original_Maximum : 3057.0\n",
      "\t diagnostics_Mask-original_Hash : 9dc2c3137b31fd872997d92c9a92d5178126d9d3\n",
      "\t diagnostics_Mask-original_Spacing : (0.7812499999999999, 0.7812499999999999, 6.499999999999998)\n",
      "\t diagnostics_Mask-original_Size : (256, 256, 25)\n",
      "\t diagnostics_Mask-original_BoundingBox : (162, 84, 11, 47, 70, 7)\n",
      "\t diagnostics_Mask-original_VoxelNum : 4137\n",
      "\t diagnostics_Mask-original_VolumeNum : 2\n",
      "\t diagnostics_Mask-original_CenterOfMassIndex : (186.98549673676578, 106.3562968334542, 14.38917089678511)\n",
      "\t diagnostics_Mask-original_CenterOfMass : (46.47304432559825, 16.518518098863908, 15.529610829103234)\n",
      "\t original_shape_VoxelVolume : 16412.658691406243\n",
      "\t original_shape_Maximum3DDiameter : 69.60099030590368\n",
      "\t original_shape_MeshVolume : 16147.51180013021\n",
      "\t original_shape_MajorAxisLength : 61.99722046980879\n",
      "\t original_shape_Sphericity : 0.4798234536231475\n",
      "\t original_shape_LeastAxisLength : 28.584423185376522\n",
      "\t original_shape_Elongation : 0.5621171627174109\n",
      "\t original_shape_SurfaceVolumeRatio : 0.3987500788652454\n",
      "\t original_shape_Maximum2DDiameterSlice : 53.59397776919529\n",
      "\t original_shape_Flatness : 0.46105975346582634\n",
      "\t original_shape_SurfaceArea : 6438.821603779402\n",
      "\t original_shape_MinorAxisLength : 34.849701666854706\n",
      "\t original_shape_Maximum2DDiameterColumn : 49.490854979101925\n",
      "\t original_shape_Maximum2DDiameterRow : 65.88905951721043\n",
      "\t original_glcm_JointAverage : 16.55380772442751\n",
      "\t original_glcm_JointEntropy : 8.799696270248813\n",
      "\t original_glcm_ClusterShade : 19.605083427286676\n",
      "\t original_glcm_MaximumProbability : 0.007352392266290182\n",
      "\t original_glcm_Idmn : 0.961402169623227\n",
      "\t original_glcm_JointEnergy : 0.002893149242988865\n",
      "\t original_glcm_Contrast : 47.492125114429776\n",
      "\t original_glcm_DifferenceEntropy : 3.74406097806642\n",
      "\t original_glcm_InverseVariance : 0.19881884197093194\n",
      "\t original_glcm_DifferenceVariance : 16.65563705027098\n",
      "\t original_glcm_Idn : 0.8726052157397169\n",
      "\t original_glcm_Idm : 0.20022255640475703\n",
      "\t original_glcm_Correlation : 0.3917522006696661\n",
      "\t original_glcm_Autocorrelation : 289.5436994017259\n",
      "\t original_glcm_SumEntropy : 5.354241321485615\n",
      "\t original_glcm_SumSquares : 39.05587959224222\n",
      "\t original_glcm_ClusterProminence : 27995.937591943148\n",
      "\t original_glcm_Imc2 : 0.6942249020670357\n",
      "\t original_glcm_Imc1 : -0.09438938808738298\n",
      "\t original_glcm_DifferenceAverage : 5.284468789866316\n",
      "\t original_glcm_Id : 0.28722572382985156\n",
      "\t original_glcm_ClusterTendency : 108.73139325453903\n",
      "\t original_gldm_GrayLevelVariance : 39.19271419906397\n",
      "\t original_gldm_HighGrayLevelEmphasis : 280.4065748126662\n",
      "\t original_gldm_DependenceEntropy : 6.885019899269458\n",
      "\t original_gldm_DependenceNonUniformity : 936.6601401982113\n",
      "\t original_gldm_GrayLevelNonUniformity : 186.8143582306019\n",
      "\t original_gldm_SmallDependenceEmphasis : 0.37960167130711403\n",
      "\t original_gldm_SmallDependenceHighGrayLevelEmphasis : 110.30563945728201\n",
      "\t original_gldm_DependenceNonUniformityNormalized : 0.22641047623838803\n",
      "\t original_gldm_LargeDependenceEmphasis : 8.661590524534686\n",
      "\t original_gldm_LargeDependenceLowGrayLevelEmphasis : 0.07650590736710827\n",
      "\t original_gldm_DependenceVariance : 2.1619872286911965\n",
      "\t original_gldm_LargeDependenceHighGrayLevelEmphasis : 2335.0519700265895\n",
      "\t original_gldm_SmallDependenceLowGrayLevelEmphasis : 0.0035453562622343696\n",
      "\t original_gldm_LowGrayLevelEmphasis : 0.00860027409479837\n",
      "\t original_firstorder_InterquartileRange : 253.0\n",
      "\t original_firstorder_Skewness : 0.27565085908587594\n",
      "\t original_firstorder_Uniformity : 0.045156963555862184\n",
      "\t original_firstorder_Median : 812.0\n",
      "\t original_firstorder_Energy : 2918821481.0\n",
      "\t original_firstorder_RobustMeanAbsoluteDeviation : 103.00138343026683\n",
      "\t original_firstorder_MeanAbsoluteDeviation : 133.44726195252767\n",
      "\t original_firstorder_TotalEnergy : 11579797135.314934\n",
      "\t original_firstorder_Maximum : 1266.0\n",
      "\t original_firstorder_RootMeanSquared : 839.9646448180755\n",
      "\t original_firstorder_90Percentile : 1044.4\n",
      "\t original_firstorder_Minimum : 468.0\n",
      "\t original_firstorder_Entropy : 4.601935553903786\n",
      "\t original_firstorder_Range : 798.0\n",
      "\t original_firstorder_Variance : 24527.07920837261\n",
      "\t original_firstorder_10Percentile : 632.0\n",
      "\t original_firstorder_Kurtosis : 2.1807729393860265\n",
      "\t original_firstorder_Mean : 825.2354363065023\n",
      "\t original_glrlm_ShortRunLowGrayLevelEmphasis : 0.008229766244155428\n",
      "\t original_glrlm_GrayLevelVariance : 39.118151021979244\n",
      "\t original_glrlm_LowGrayLevelRunEmphasis : 0.008600397891661503\n",
      "\t original_glrlm_GrayLevelNonUniformityNormalized : 0.04514123814981055\n",
      "\t original_glrlm_RunVariance : 0.08479457789590625\n",
      "\t original_glrlm_GrayLevelNonUniformity : 175.6351923150419\n",
      "\t original_glrlm_LongRunEmphasis : 1.2268440382584342\n",
      "\t original_glrlm_ShortRunHighGrayLevelEmphasis : 268.9741798411307\n",
      "\t original_glrlm_RunLengthNonUniformity : 3500.0432315746298\n",
      "\t original_glrlm_ShortRunEmphasis : 0.9559391731405504\n",
      "\t original_glrlm_LongRunHighGrayLevelEmphasis : 341.2865790983503\n",
      "\t original_glrlm_RunPercentage : 0.9404064632491029\n",
      "\t original_glrlm_LongRunLowGrayLevelEmphasis : 0.010601170478748765\n",
      "\t original_glrlm_RunEntropy : 4.915038003159503\n",
      "\t original_glrlm_HighGrayLevelRunEmphasis : 281.066493908972\n",
      "\t original_glrlm_RunLengthNonUniformityNormalized : 0.8950494659480998\n",
      "\t original_glszm_GrayLevelVariance : 40.60313992393263\n",
      "\t original_glszm_ZoneVariance : 8.721239097486347\n",
      "\t original_glszm_GrayLevelNonUniformityNormalized : 0.044057307901283996\n",
      "\t original_glszm_SizeZoneNonUniformityNormalized : 0.3997843804512568\n",
      "\t original_glszm_SizeZoneNonUniformity : 747.5967914438503\n",
      "\t original_glszm_GrayLevelNonUniformity : 82.38716577540107\n",
      "\t original_glszm_LargeAreaEmphasis : 13.615508021390374\n",
      "\t original_glszm_SmallAreaHighGrayLevelEmphasis : 193.438051925864\n",
      "\t original_glszm_ZonePercentage : 0.4520183708000967\n",
      "\t original_glszm_LargeAreaLowGrayLevelEmphasis : 0.12723841553344326\n",
      "\t original_glszm_LargeAreaHighGrayLevelEmphasis : 3514.7614973262034\n",
      "\t original_glszm_HighGrayLevelZoneEmphasis : 288.6235294117647\n",
      "\t original_glszm_SmallAreaEmphasis : 0.6564478999587141\n",
      "\t original_glszm_LowGrayLevelZoneEmphasis : 0.009100942027706215\n",
      "\t original_glszm_ZoneEntropy : 6.50821498619819\n",
      "\t original_glszm_SmallAreaLowGrayLevelEmphasis : 0.006416982055097711\n"
     ]
    }
   ],
   "source": [
    "print('Result type:', type(result))  # result is returned in a Python ordered dictionary)\n",
    "print('')\n",
    "print('Calculated features')\n",
    "for key, value in result.items():\n",
    "    print('\\t', key, ':', value)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
